// API服务配置
const BASE_URL = '/api'
// 请求拦截器
const request = async (url, options = {}) => {
  const config = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  }

  // 添加认证token
  const token = localStorage.getItem('token')
  if (token && !url.includes('/auth/login')) {
    config.headers.Authorization = `Bearer ${token}`
  }

  try {
    const response = await fetch(`${BASE_URL}${url}`, config)
    if (!response.ok) {
      throw response
    }
    const data = await response.json()

    if (data.code === 401) {
      // token失效，跳转到登录页
      localStorage.removeItem('token')
      window.location.href = '/'
      return
    }

    return data
  } catch (error) {
    console.error('API请求错误:', error)
    if (error instanceof Response) {
      if (error.status === 401) {
        // token失效，跳转到登录页
        localStorage.removeItem('token')
        window.location.href = '/'
        return
      }
    }
    throw error
  }
}

// 认证与授权模块
export const authAPI = {
  // 用户登录
  login: (data) =>
    request('/auth/login', {
      method: 'POST',
      body: JSON.stringify(data),
    }),

  // 修改密码
  changePassword: (data) =>
    request('/auth/change-password', {
      method: 'PUT',
      body: JSON.stringify(data),
    }),
}

// 数据看板模块
export const dashboardAPI = {
  // 获取概览数据
  getOverview: () => request('/dashboard/overview'),

  // 获取公共资源分类数据
  getPublicResourcesData: () => request('/dashboard/public-resources'),

  // 获取人才站点统计数据
  getServiceData: () => request('/dashboard/talent-stations'),
}

// 分类管理模块
export const categoryAPI = {
  // 获取分类列表
  getList: (type) => request(`/categories?type=${type}`),

  // 新增分类
  create: (data) =>
    request('/categories', {
      method: 'POST',
      body: JSON.stringify(data),
    }),

  // 编辑分类
  update: (id, data) =>
    request(`/categories/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    }),

  // 删除分类
  delete: (id) =>
    request(`/categories/${id}`, {
      method: 'DELETE',
    }),

  // 分类排序
  sort: (data) =>
    request('/categories/sort', {
      method: 'PUT',
      body: JSON.stringify(data),
    }),
}

// 点位管理模块
export const spotAPI = {
  // 获取点位列表
  getList: (params) => {
    const query = new URLSearchParams(params).toString()
    return request(`/spots?${query}`)
  },

  // 新增点位
  create: (data) =>
    request('/spots', {
      method: 'POST',
      body: JSON.stringify(data),
    }),

  // 编辑点位
  update: (id, data) =>
    request(`/spots/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    }),

  // 批量删除点位
  deleteByIds: (ids) => {
    const params = new URLSearchParams()
    ids.forEach((id) => params.append('ids', id))
    return request(`/spots?${params.toString()}`, {
      method: 'DELETE',
    })
  },

  // 导入点位
  import: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return request('/spots/import', {
      method: 'POST',
      body: formData,
      headers: {}, // 清空headers让浏览器自动设置Content-Type
    })
  },

  // 查询导入进度
  getImportProgress: () => {
    return request(`/spots/import/status`)
  },

  stopImport: () => {
    return request(`/spots/import/stop`, {
      method: 'POST',
    })
  },

  // 下载导入模板
  downloadTemplate: () => {
    return fetch(`${BASE_URL}/spots/template`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`,
      },
    })
  },

  // 导出点位
  export: (params) => {
    const query = new URLSearchParams(params).toString()
    return fetch(`${BASE_URL}/spots/export?${query}`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`,
      },
    })
  },

  // 获取点位已分配的服务
  getAssignedServices: (spotId) => request(`/spots/${spotId}/services`),

  // 分配服务到点位
  assignServices: (spotId, serviceIds) =>
    request(`/spots/${spotId}/services`, {
      method: 'POST',
      body: JSON.stringify({ serviceIds }),
    }),
}

// 用户管理模块
export const userAPI = {
  // 获取用户列表
  getList: (params) => {
    const query = new URLSearchParams(params).toString()
    return request(`/users?${query}`)
  },

  // 新增用户
  create: (data) =>
    request('/users', {
      method: 'POST',
      body: JSON.stringify(data),
    }),

  // 编辑用户
  update: (id, data) =>
    request(`/users/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    }),

  // 删除用户
  delete: (id) =>
    request(`/users/${id}`, {
      method: 'DELETE',
    }),

  // 重置用户密码
  resetPassword: (id, data) =>
    request(`/users/${id}/reset-password`, {
      method: 'PUT',
      body: JSON.stringify(data),
    }),
}

// 操作日志模块
export const logAPI = {
  // 获取操作日志
  getList: (params) => {
    const query = new URLSearchParams(params).toString()
    return request(`/logs?${query}`)
  },
}

// 文件上传模块
export const uploadAPI = {
  // 上传文件
  uploadFile: (file, type) => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', type)
    return request('/upload/file', {
      method: 'POST',
      body: formData,
      headers: {}, // 清空headers让浏览器自动设置Content-Type
    })
  },
}

// 首页管理模块
export const homeAPI = {
  // 获取首页设置
  getHomeSettings: () => request('/home/settings'),

  // 保存首页设置
  saveHomeSettings: (data) =>
    request('/home/settings', {
      method: 'POST',
      body: JSON.stringify(data),
    }),
}

// 服务菜单管理模块
export const menuAPI = {
  // 获取菜单树形结构
  getTree: (params) => {
    const query = new URLSearchParams(params).toString()
    return request(`/menus/tree?${query}`, {
      method: 'GET',
    })
  },
  // 获取顶部服务菜单
  getTopMenu: () => {
    return request('/menus/top-menu', {
      method: 'GET',
    })
  },
  // 创建菜单
  create: (data) =>
    request('/menus', {
      method: 'POST',
      body: JSON.stringify(data),
    }),

  // 更新菜单
  update: (id, data) =>
    request(`/menus/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    }),

  // 删除菜单
  delete: (id) =>
    request(`/menus/${id}`, {
      method: 'DELETE',
    }),

  // 导入点位
  import: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return request('/menus/import', {
      method: 'POST',
      body: formData,
      headers: {}, // 清空headers让浏览器自动设置Content-Type
    })
  },

  // 下载菜单导入模板
  downloadTemplate: () => {
    return fetch(`${BASE_URL}/menus/template`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`,
      },
    })
  },
}

// 公告管理模块
export const noticeAPI = {
  // 分页查询公告
  getList: (params) => {
    const query = new URLSearchParams(params).toString()
    return request(`/notices?${query}`)
  },

  // 根据ID查询公告
  getById: (id) => request(`/notices/${id}`),

  // 新增公告
  create: (data) =>
    request('/notices', {
      method: 'POST',
      body: JSON.stringify(data),
    }),

  // 更新公告
  update: (id, data) =>
    request(`/notices/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    }),

  // 删除公告
  delete: (id) =>
    request(`/notices/${id}`, {
      method: 'DELETE',
    }),

  // 批量删除公告
  deleteByIds: (ids) => {
    const params = new URLSearchParams()
    ids.forEach((id) => params.append('ids', id))
    return request(`/notices?${params.toString()}`, {
      method: 'DELETE',
    })
  },
}

// 公告轮播管理模块
export const noticeBannerAPI = {
  // 获取轮播列表（按排序顺序）
  getList: () => request('/notice-banners'),

  // 批量添加轮播公告
  batchAdd: (noticeIds) =>
    request('/notice-banners/batch', {
      method: 'POST',
      body: JSON.stringify({ noticeIds }),
    }),

  // 删除轮播公告
  delete: (id) =>
    request(`/notice-banners/${id}`, {
      method: 'DELETE',
    }),

  // 更新轮播状态
  updateStatus: (id, status) =>
    request(`/notice-banners/${id}/status`, {
      method: 'PUT',
      body: JSON.stringify({ status }),
    }),

  // 交换排序（用于上移下移）
  swapSort: (id1, id2) =>
    request('/notice-banners/swap-sort', {
      method: 'PUT',
      body: JSON.stringify({ id1, id2 }),
    }),
}

export default {
  authAPI,
  dashboardAPI,
  categoryAPI,
  spotAPI,
  userAPI,
  logAPI,
  uploadAPI,
  menuAPI,
  homeAPI,
  noticeAPI,
  noticeBannerAPI,
}
